import UIKit
import Flutter
import CoreTelephony

@UIApplicationMain
@objc class AppDelegate: FlutterAppDelegate {
    
    private var callCenter : CTCallCenter?
    private var isConnected : Bool = false
    private var isFromSelf : Bool = false
    
    override func application(_ application: UIApplication,didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
    ) -> Bool {
        GeneratedPluginRegistrant.register(with: self)
        let controller : FlutterViewController = window?.rootViewController as! FlutterViewController
        let channel = FlutterMethodChannel(name: "cn.jtkj.yh_car_app/telephony", binaryMessenger: controller.binaryMessenger)
        channel.setMethodCallHandler({ (call: FlutterMethodCall, result: @escaping FlutterResult) -> Void in
            guard call.method == "dialPhoneNumber" else {
                result(FlutterMethodNotImplemented)
                return
            }
            
            if let dict = call.arguments as? Dictionary<String, Any> {
                let phoneNumber:String = dict["phoneNumber"] as? String ?? ""
                if(phoneNumber != "") {
                    self.isFromSelf = true;
                    self.callPhoneNumber(phoneNumber: phoneNumber, result: result)
                } else {
                    result(FlutterError(code: "InvalidArguments", message: "Invalid phone number", details: nil))
                    return
                }
            }
        })
        
        return super.application(application, didFinishLaunchingWithOptions: launchOptions)
    }
    
    override func applicationDidEnterBackground(_ application: UIApplication) {
        super.applicationDidEnterBackground(application)
        
        print("进入后台")
    }
    
    override func applicationWillEnterForeground(_ application: UIApplication) {
        super.applicationWillEnterForeground(application)
        
        print("进入前台")
    }
    
    
    func callPhoneNumber(phoneNumber: String, result: @escaping FlutterResult) {
        if let url = URL(string: "tel://\(phoneNumber)") {
            if UIApplication.shared.canOpenURL(url) {
                UIApplication.shared.open(url, options: [:]) { (isSuccess) in
                    if(!isSuccess){
                        return
                    }
                    weak var weakSelf = self
                    //设置电话代理
                    self.callCenter = CTCallCenter()
                    self.callCenter!.callEventHandler = { (call: CTCall) in
                        DispatchQueue.main.async(execute: {
                            weakSelf?.handle(call)
                        })
                    }
                }
                result(nil)
            } else {
                result(FlutterError(code: "CannotOpenPhone", message: "Cannot open phone app", details: nil))
            }
        } else {
            result(FlutterError(code: "InvalidPhoneNumber", message: "Invalid phone number", details: nil))
        }
    }
    
    func handle(_ call : CTCall?) {
        if call?.callState == CTCallStateDialing {
            //方法通道
            if(self.isFromSelf == true) {
                let message : Dictionary<String, Any> = ["msg":"call_hold"]
                self.sendMessage2Flutter(message: message)
            }
        } else if call?.callState == CTCallStateConnected {
            self.isConnected = true
        } else if call?.callState == CTCallStateDisconnected {
            var message : Dictionary<String, Any> = [:];
            if(self.isConnected == true) {
                //方法通道
                message = ["msg":"call_up", "duration":-1]
            } else {
                message = ["msg":"call_up", "duration":0]
            }
            if (self.isFromSelf == true) {
                self.sendMessage2Flutter(message: message)
                self.isConnected = false
                self.isFromSelf = false
            }
        }
    }
    
    func sendMessage2Flutter(message: Dictionary<String, Any>) {
        let controller : FlutterViewController = window?.rootViewController as! FlutterViewController
        let channel = FlutterMethodChannel(name: "cn.jtkj.yh_car_app/holdUp", binaryMessenger: controller.binaryMessenger)
        channel.invokeMethod("onTelephonyEvent", arguments: message, result: { (callback: Any) -> Void in
            print(callback)
        })
    }
}
